<?php

namespace App\Console\Commands\model;
;

use App\Dep\SystemDep;
use App\Dep\TextToImageDep;
use App\Dep\VideoTaskDep;
use App\Service\UidService;
use Illuminate\Console\Command;

class VideoCmd extends Command
{
    //打标
    public $signature = 'model:text-to-video';

    public function handle()
    {
        $dep = new TextToImageDep();
        $resWait = $dep->getWaitVideo();
        if ($resWait->isEmpty()) {
            $this->log('have no wait video');
            return false;
        }


        $systemDep = new SystemDep();
        $videoTaskDep = new VideoTaskDep();

        $notDealTask = $videoTaskDep->getWaitTask('text_to_image');
        if($notDealTask->count() >= 3){
            $this->log('task is full,need wait');
            return false;
        }
        $resSystem = $systemDep->first();

        $resWait->each(function ($item) use ($dep, $videoTaskDep,$resSystem) {
            $uuid = UidService::textToImageUid();
            $pictureArr = [];
            $imageArr = json_decode($item->image_res_arr,true);
            foreach ($imageArr as $image){
                $pictureArr[] = [
                  "path" => "{$resSystem->text_to_image_dir}\\{$image}",
                  "time" => $item->per_second
                ];
            }
            $input = [
                "inputpath" => "{$resSystem->text_to_image_dir}\\pictovideo.mp4",
                "outputpath" => "{$resSystem->text_to_image_dir}\\{$uuid}.mp4",
                "fps" => $item->video_fps,
                "bit" => $item->video_bit,
                "gpu" => 0,
                "function" => [[
                    "act" => "pictovideo",
                    "out_w" => "720",
                    "out_h" => "1280",
                    'pictures'=> $pictureArr,
                ]]
            ];

            $data = [
                'type' => 'text_to_image',
                'type_id' => $item->id,
                'data' => json_encode($input),
                'result' =>  ""
            ];
            $res = $videoTaskDep->add($data);

            $updData = [
              'video_task_id' => $res,
              'video' => "{$uuid}.mp4",
              'cover' => isset($imageArr[0]) ? $imageArr[0] : "",
            ];
            $dep->edit($item->id,$updData);
            $this->log("add task",['id'=> $item->id]);
        });
    }

    private function log($msg, $context = [])
    {
        $this->info("text to image log: {$msg} " . json_encode($context, JSON_UNESCAPED_UNICODE));
        log_daily("text-to-video")->info($msg, $context);
    }


}
